package cn.tworice.common.util.file;

import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;

public class FileConvertUtil {

    public static String convertToBase64(MultipartFile mFile) throws Exception{
        BASE64Encoder bEncoder=new BASE64Encoder();
        String[] suffix= Objects.requireNonNull(mFile.getOriginalFilename()).split("\\.");
        String prefix="data:image/jpg;base64,".replace("jpg", suffix[suffix.length - 1]);
        return prefix + bEncoder.encode(mFile.getBytes()).replaceAll("[\\s*\t\n\r]", "");
    }

    public static BufferedImage convert(MultipartFile file) throws IOException {
        try (InputStream inputStream = file.getInputStream()) {
            return ImageIO.read(inputStream);
        }
    }

    /**
     * BufferedImage 转Base64
     * @param bufferedImage 图片
     * @return java.lang.String Base64
     * @author 二饭 [2023/2/17]
     **/
    public static String convertToBase64(BufferedImage bufferedImage) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();//io流
        try {
            ImageIO.write(bufferedImage, "png", baos);//写入流中
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] bytes = baos.toByteArray();//转换成字节
        BASE64Encoder encoder = new BASE64Encoder();
        String png_base64 = encoder.encodeBuffer(bytes).trim();//转换成base64串
        png_base64 = png_base64.replaceAll("\n", "").replaceAll("\r", "");//删除 \r\n
        System.out.println("值为：" + "data:image/jpg;base64," + png_base64);
        return "data:image/jpg;base64," + png_base64;
    }
}
